package gsw.tool.json;

import java.lang.reflect.Type;

import gsw.tool.json.deserializer.ObjectDeserializer;
import gsw.tool.json.serializer.ObjectSerializer;

/**
 * Json解析框架
 */
public class JSON {

    /**
     * 将对象转为json格式的字符串
     */
    public static String toJSONString(Object object) {
        ObjectSerializer serializer = JsonConfig.getGlobalInstance().getSerializer(object.getClass());
        StringBuilder sb = new StringBuilder();
        serializer.serializer(JsonConfig.getGlobalInstance(), sb, object);
        return sb.toString();
    }

    /**
     * 将json格式的字符串转为对象
     */
    public static <T> T parse(String json, Class<T> clazz) {
        return parse(json, (Type) clazz);
    }

    /**
     * 将json格式的字符串转为对象
     */
    public static <T> T parse(String json, Type type) {
        ObjectDeserializer deserializer = JsonConfig.getGlobalInstance().getDeserializer(type);
        try {
            return deserializer.deserializer(JsonConfig.getGlobalInstance(), json, null);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
